package com.mlm.mlmapp.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyLayoutManager;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.adapter.view.RVDivider;
import com.mlm.mlmapp.adapter.view.listener.DresserClickListener;
import com.mlm.mlmapp.adapter.view.listener.OnNextPageShouldDownloadListener;
import com.mlm.mlmapp.adapter.view.listener.OnRcvScrollListener;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EActivity(R.layout.hairdresserlist)
public class HairDresserListActivity extends BaseActivity implements HTTPCons,
        DresserClickListener {
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    public static final int DESC = 1;
    public static final int ASC = 2;
    public static final int NORMAL = 0;
    public static final String POST_LIST = "post_list";
    public static final String STUDIO_LIST = "mendian_list";
    public static final String RATING_DESC = "rating_desc";
    public static final String CITY_LIST = "city_list";
    public static final String CITY_REFRESH = "cityrefresh";
    private String post_list = "";
    private String studio_list = "";
    private String rating_desc = "";
    private String city_lists = "";
    private String city_name="";
    private AQuery aq;
    private DresserlistAdapter adapter;
    List<JSONObject> dresserListDataset;
    private int btnStatusPrice;
    private int btnStatusOrder;
    private String currentPrice = "";
    private String currentOrder = "";
    private String dresserName = "";
    @ViewById
    RecyclerView rv_dresser;
    @ViewById
    LinearLayout btn_back;
    @ViewById
    RelativeLayout btn_search;
    @ViewById
    RelativeLayout search_layout;
    @ViewById
    ImageButton iv_search;
    @ViewById
    LinearLayout bottom_bar;
    @ViewById
    Button btn_area;
    @ViewById
    TextView btnSearch;
    @ViewById
    Button btn_price;
    @ViewById
    Button btn_order;
    @ViewById
    RecyclerView rv_city;
    @ViewById
    RecyclerView rv_studio;
    @ViewById
    Button btn_dresser_type;
    @ViewById
    EditText etSearch;
    @ViewById
    ImageView ivDeleteText;
    @ViewById
    TextView city;
    @ViewById
    LinearLayout city_list;
    @ViewById
    RecyclerView rv_type;
    @ViewById
    RelativeLayout more;
    @ViewById
    RelativeLayout rl_area;
    @ViewById
    Button btn_all;
    String localeCityName;
    String currCity;
    @Extra
    boolean bookflag;
    @ColorRes(R.color.red)
    int redText;
    @ColorRes(R.color.lightgreytext)
    int greytext;
    public final static int CITY_LIST_REQUEST_CODE=929;
    Bitmap preset;
    List<JSONObject> citys = new ArrayList<>();
    List<JSONObject> studios = new ArrayList<>();
    Map<String, JSONArray> studiosMap = new HashMap<String, JSONArray>();
    String studioid = "";
    String areakey = "全部区域";

    @DimensionRes(R.dimen.recyclerview_sylist_space)
    float recyclerview_sylist_space;
    int mPage = 1;
    private String[] data = new String[]{"智能排序", "美单最高", "价格最高", "价格最低"};
    private MyAdapter mAdapter;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);

    }
@OnActivityResult(CITY_LIST_REQUEST_CODE)
void onCityListResult(int resultCode,Intent data){
    if(resultCode==RESULT_CANCELED){
        return;
    }
    if(data!=null){
        currCity=data.getStringExtra("cityName");
        if(city_name.equals(currCity)){
            return;
        }
        city_name=currCity;
        if (city_name != null && !city_name.equals("")) {
            city.setText(city_name);
            clearArea();
            clearDataset();
            updateDataset(mPage);
        }
    }

}


    @AfterViews
    public void init() {
        //定位
        preset = BitmapFactory.decodeResource(this.getResources(), R.drawable.style_default);
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        initLocation();
        mLocationClient.start();
        rv_type.setHasFixedSize(true);
        LinearLayoutManager typeLayoutManager = new SyLayoutManager(this);
        rv_type.setLayoutManager(typeLayoutManager);
        typeLayoutManager.setOrientation(OrientationHelper.VERTICAL);
//        rv_type.addItemDecoration(new RVDivider(this,RVDivider.VERTICAL_LIST));
//        RVDivider divider=new RVDivider(RVDivider.VERTICAL);
//        divider.setSize(1);
//        divider.setColor(Color.parseColor("#9a9a9a"));
//        rv_type.addItemDecoration(divider);
        mAdapter = new MyAdapter(data);
        rv_type.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new MyAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, String data) {
                switch (data) {
                    case "智能排序":
                        currentPrice = "";
                        currentOrder = "";

                        btn_all.setText("智能排序");
                        btn_all.setTextColor(greytext);
                        btn_all.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_down), null);
                        break;
                    case "价格最高":
                        currentPrice = "DESC";
                        currentOrder = "";

                        btn_all.setText("价格最高");
                        btn_all.setTextColor(redText);
                        btn_all.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_up), null);
                        break;
                    case "价格最低":
                        currentPrice = "ASC";
                        currentOrder = "";
                        btn_all.setText("价格最低");
                        btn_all.setTextColor(redText);
                        btn_all.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_up), null);
                        break;
                    case "美单最高":
                        currentOrder = "DESC";
                        currentPrice = "";
                        btn_all.setText("美单最高");
                        btn_all.setTextColor(redText);
                        btn_all.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_up), null);
                        break;
                }

                more.setVisibility(View.INVISIBLE);
                clearDataset();
                updateDataset(mPage);
//                Toast.makeText(HairDresserListActivity.this, data, Toast.LENGTH_SHORT).show();

            }
        });

        btn_search.setVisibility(View.VISIBLE);
        btn_dresser.setCompoundDrawablesWithIntrinsicBounds(null,
                getResources().getDrawable(R.drawable.dresserchecked), null,
                null);
        btn_dresser.setTextColor(getResources().getColor(R.color.red));

        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }
        etSearch.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // TODO Auto-generated method stub

            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    ivDeleteText.setVisibility(View.GONE);
                } else {
                    ivDeleteText.setVisibility(View.VISIBLE);
                }
            }
        });

        aq = new AQuery(this);
        aq.hardwareAccelerated11();
        dresserListDataset = new ArrayList<>();
        LinearLayoutManager linearManager = new LinearLayoutManager(this);
//        final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);
        rv_dresser.setLayoutManager(linearManager);
        rv_dresser.setHasFixedSize(true);
        rv_dresser.addItemDecoration(new GridMarginDecoration(this, 0, 0, 0,
                recyclerview_sylist_space));
        rv_dresser.setItemAnimator(new RecyclAnimation());
        OnRcvScrollListener listener = new OnRcvScrollListener() {

            @Override
            public void onBottom() {
                // TODO Auto-generated method stub
                super.onBottom();
                // mSwipeRefreshWidget.setRefreshing(true);
                updateDataset(mPage);
            }

        };
        rv_dresser.setOnScrollListener(listener);
        adapter = new DresserlistAdapter(HairDresserListActivity.this,
                dresserListDataset);
        rv_dresser.setAdapter(adapter);
        // init sylist date
        updateDataset(mPage);
        rl_area.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                clearPopup();
            }
        });
        more.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                clearPopup();
            }
        });
    }


    @OnActivityResult(REQUEST_CODE)
    void onResult(Intent data) {
        if (data != null) {

            this.post_list = data.getStringExtra(POST_LIST);
            this.studio_list = data.getStringExtra(STUDIO_LIST);
            this.city_lists = data.getStringExtra(CITY_LIST);
//          z
//  this.rating_desc = data.getStringExtra(RATING_DESC);
//            if (!"".equals(post_list) || !"".equals(studio_list)
//                    || !"".equals(rating_desc)) {
            if (!"".equals(post_list)) {
                btn_dresser_type.setTextColor(redText);
                btn_dresser_type.setCompoundDrawables(null, null,
                        CommonUtils.setButtonDrawableRight(this,
                                R.drawable.filter_select), null);
            } else {
                btn_dresser_type.setTextColor(greytext);
                btn_dresser_type.setCompoundDrawables(null, null,
                        CommonUtils.setButtonDrawableRight(this,
                                R.drawable.filter_default), null);
            }
            clearDataset();
            updateDataset(mPage);
        }
    }

    @Click
    void ivDeleteText() {
        etSearch.setText("");
    }

    @Click
    void btnSearch() {
//        Toast.makeText(HairDresserListActivity.this, "quxiao", Toast.LENGTH_SHORT).show();
        etSearch.setText("");
        search_layout.setVisibility(View.GONE);
        clearDataset();
        dresserName = "";
        updateDataset(mPage);
    }

    private void clearPopup() {
        if (more.getVisibility() == View.VISIBLE)
            more.setVisibility(View.INVISIBLE);
        if (rl_area.getVisibility() == View.VISIBLE)
            rl_area.setVisibility(View.INVISIBLE);
    }

    @Click
    void iv_search() {
        clearPopup();
        search_layout.setVisibility(View.VISIBLE);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(HairDresserListActivity.this.INPUT_METHOD_SERVICE);
                    //隐藏键盘
                    imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
//                    Toast.makeText(HairDresserListActivity.this, "点击了搜索", Toast.LENGTH_SHORT).show();
                    dresserName = etSearch.getText().toString().trim();
                    clearDataset();
                    updateDataset(mPage);
                    return true;
                }
                return false;
            }
        });
    }


    @Click
    void btn_dresser_type() {
        clearPopup();
        HairDresserFilterActivity_.intent(this).extra("postIDs", post_list).extra("studioIDs", studio_list).startForResult(REQUEST_CODE);
    }

//    /**
//     * 按价格
//     * desc default,arrow up as ASC, down as DESC
//     */
//    @Click
//    void btn_price() {
//        switch (btnStatusPrice) {
//            case 0:
//                btnStatusPrice = 1;
//                currentPrice = "ASC";
//                btn_price.setCompoundDrawables(null, null, CommonUtils
//                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
//                btn_price.setTextColor(redText);
//                break;
//            case 1:
//                btnStatusPrice = 2;
//                currentPrice = "DESC";
//                btn_price.setCompoundDrawables(null, null, CommonUtils
//                        .setButtonDrawableRight(this, R.drawable.arrow_down), null);
//                btn_price.setTextColor(redText);
//                break;
//            case 2:
//            default:
//                currentPrice = "ASC";
//                btnStatusPrice = 1;
//                btn_price.setCompoundDrawables(null, null, CommonUtils
//                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
//                btn_price.setTextColor(redText);
//        }
//        clearDataset();
//        updateDataset(mPage);
//    }

//    /**
//     * desc default
//     * 按订单
//     */
//    @Click
//    void btn_order() {
//
//        switch (btnStatusOrder) {
//            case 0:
//                btnStatusOrder = 1;
//                currentOrder = "ASC";
//                btn_order.setCompoundDrawables(null, null, CommonUtils
//                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
//                btn_order.setTextColor(redText);
//                break;
//            case 1:
//                btnStatusOrder = 2;
//                currentOrder = "DESC";
//                btn_order.setCompoundDrawables(null, null, CommonUtils
//                        .setButtonDrawableRight(this, R.drawable.arrow_down), null);
//                btn_order.setTextColor(redText);
//                break;
//            case 2:
//            default:
//                currentOrder = "ASC";
//
//                btnStatusOrder = 1;
//                btn_order.setCompoundDrawables(null, null, CommonUtils
//                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
//                btn_order.setTextColor(redText);
//        }
//        clearDataset();
//        updateDataset(mPage);
//    }

    // when change the condition, need clear dataset
    private void clearDataset() {
        mPage = 1;
        this.dresserListDataset.clear();
        adapter.notifyDataSetChanged();
    }

    // values bought starLevel levlId studioId
    void updateDataset(int page) {
        StringBuilder url = new StringBuilder(get_dresser_list_action);
        url.append("?");
        if (!"".equals(currentPrice)) {
            url.append("values=" + currentPrice);
            url.append("&");
        }

        if (!"".equals(currentOrder)) {
            url.append("bought=" + currentOrder);
            url.append("&");
        }

        if (!"".equals(rating_desc)) {
            url.append("starLevel=" + rating_desc);
            url.append("&");
        }

        if (!"".equals(post_list)) {
            url.append("levlId=" + post_list);
            url.append("&");
        }

        if (!"".equals(studio_list)) {
            url.append("studioId=" + studio_list);
            url.append("&");
        }

        if (!"".equals(dresserName)) {
            url.append("stylistName=" + dresserName);
            url.append("&");
        }
        if (!"".equals(city_name)) {
            url.append("cityName=" + city_name);
            url.append("&");
        }
        if (!"".equals(studioid)) {
            url.append("studioId=" + studioid);
            url.append("&");
        }
        url.append("page=" + page);
        getSylist(url.toString());

    }

    void getSylist(String url) {
        aq.progress(new AQProgressDialog(this)).ajax(url, JSONArray.class, new AjaxCallback<JSONArray>() {

            @Override
            public void callback(String url, JSONArray object, AjaxStatus status) {
                // TODO Auto-generated method stub
                super.callback(url, object, status);
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                int startIndex = dresserListDataset.size();
                if(object != null &&object.length()==0){
                    Toast.makeText(HairDresserListActivity.this, "没有更多内容了", Toast.LENGTH_SHORT).show();
                }
                if (object != null && object.length() > 0) {

                    for (int i = 0; i < object.length(); i++) {
                        try {
                            dresserListDataset.add(object.getJSONObject(i));
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    adapter.notifyItemRangeInserted(startIndex, object.length());
                    mPage++;
                }
            }

        });

    }

    void getStudio() {


        aq.progress(new AQProgressDialog(this)).ajax(city_filter_action + com.mlm.mlmapp.cons.Constants.CITY, JSONArray.class, new AjaxCallback<JSONArray>() {

            @Override
            public void callback(String url, JSONArray object, AjaxStatus status) {
                // TODO Auto-generated method stub
                super.callback(url, object, status);
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                citys.clear();
                studiosMap.clear();
                try {
                    JSONArray a = new JSONArray();

                    JSONObject allObj = new JSONObject();
                    allObj.put("area", "全部区域");

                    JSONObject defaultAll = new JSONObject();
                    defaultAll.put("names", "全部区域");
                    citys.add(allObj);
                    a.put(defaultAll);
                    for (int i = 0; i < object.length(); i++) {
                        JSONObject cityObj = object.getJSONObject(i);
                        citys.add(cityObj);
                        JSONArray studioArr = cityObj.getJSONArray("studioLst");
                        studiosMap.put(cityObj.getString("area"), studioArr);
                        for (int j = 0; j < studioArr.length(); j++) {

                            a.put(studioArr.getJSONObject(j));
                        }
                    }
                    studiosMap.put("全部区域", a);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                rl_area.setVisibility(View.VISIBLE);
                RecyclerView.LayoutManager cityManager = new SyLayoutManager(HairDresserListActivity.this);
                rv_city.setLayoutManager(cityManager);
                RecyclerView.LayoutManager studioManager = new SyLayoutManager(HairDresserListActivity.this);
                rv_studio.setLayoutManager(studioManager);
                rv_city.setHasFixedSize(true);
                rv_studio.setHasFixedSize(true);
                rv_studio.addItemDecoration(new RVDivider().setSize(1).setColor(Color.parseColor("#dddddd")));
                rv_city.setAdapter(new CityAdapter(HairDresserListActivity.this, citys));
                rv_studio.setAdapter(new StudioAdapter(HairDresserListActivity.this, studios));
                if (areakey == null || "".equals(areakey) || !studiosMap.containsKey(areakey)) {
                    areakey = "全部区域";
                }
                refreshRecyclerView(areakey);
//                    dialog = new CityFilterDialog(aq.getContext(), new DialogListener() {
//                        @Override
//                        public void onApply(JSONObject obj, String clazz) {
//                            HairDresserListActivity.this.area = CommonUtils.getJsonString(obj, "area");
//                            HairDresserListActivity.this.studioname = CommonUtils.getJsonString(obj, "studio");
//                            HairDresserListActivity.this.studioid = CommonUtils.getJsonString(obj, "studioid");
//                            HairDresserListActivity.this.btn_area.setText(studioname);
//                            clearDataset();
//                            updateDataset(mPage);
//                            dialog.dismiss();
//                        }
//
//                        @Override
//                        public void onCancel() {
//
//                        }
//                    }, object, area, studioid);
//                    dialog.show();
            }

        });

    }

    private void typeVisible(int flag) {
        if (flag == View.INVISIBLE) {
            more.setVisibility(View.INVISIBLE);
            btn_all.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_down), null);
            btn_all.setTextColor(greytext);
        } else {
            more.setVisibility(View.VISIBLE);
            btn_all.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_up), null);
            btn_all.setTextColor(redText);
        }
    }

    private void typeAreaVisible(int flag) {
        if (flag == View.INVISIBLE) {
            btn_area.setTextColor(greytext);
            rl_area.setVisibility(View.INVISIBLE);
            btn_area.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_down), null);
        } else {
            btn_area.setTextColor(redText);
            btn_area.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_up), null);
            getStudio();
        }


    }

    @Click
    void btn_all() {
        if (rl_area.getVisibility() == View.VISIBLE)
            rl_area.setVisibility(View.INVISIBLE);
//            typeAreaVisible(View.INVISIBLE);
        if (more.getVisibility() == View.VISIBLE)
            more.setVisibility(View.INVISIBLE);
//            typeVisible(View.INVISIBLE);
        else
            more.setVisibility(View.VISIBLE);
//            typeVisible(View.VISIBLE);

    }

    @Click
    void btn_area() {
        if (more.getVisibility() == View.VISIBLE)
            more.setVisibility(View.INVISIBLE);
//            typeVisible(View.INVISIBLE);


        if (rl_area.getVisibility() == View.VISIBLE)
            rl_area.setVisibility(View.INVISIBLE);
//            typeAreaVisible(View.INVISIBLE);
        else {
            getStudio();
//            typeAreaVisible(View.VISIBLE);
        }
    }


    class DresserlistAdapter extends
            Adapter<DresserlistAdapter.DresserViewHolder> {
        private OnNextPageShouldDownloadListener mOnNextPageShouldDownloadListener;
        private Context mContext;
        private DresserClickListener mOnDresserClickListener;
        private String id;
        private List<JSONObject> array;

        public DresserlistAdapter(Context con, List<JSONObject> array) {
            this.mContext = con;
            this.mOnDresserClickListener = (DresserClickListener) con;
            this.array = array;

        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        @Override
        public DresserViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
            // TODO Auto-generated method stub
            DresserViewHolder holder;
            holder = new DresserViewHolder(LayoutInflater.from(
                    HairDresserListActivity.this).inflate(
                    R.layout.hairdresser_list_item, parent, false));
            return holder;

        }

        @Override
        public void onBindViewHolder(DresserViewHolder holder, int position) {
            // TODO Auto-generated method stub

            if (array.size() <= 0) {
                return;
            }

            JSONObject obj = array.get(position);
            DresserViewHolder hHolder = holder;

            hHolder.tv_name.setText(getJsonString(obj, "name"));
            hHolder.tv_post.setText(getJsonString(obj, "leveName"));
            hHolder.tv_words.setText(getJsonString(obj, "introduce"));
            hHolder.tv_collections.setText(mContext.getString(
                    R.string.txt_collection, getJsonInt(obj, "collected")));
            hHolder.tv_orders.setText(mContext.getString(R.string.txt_order,
                    getJsonInt(obj, "bought")));
            hHolder.tv_price.setText(this.mContext.getString(
                    R.string.txt_price, getJsonInt(obj, "priceMast")));
            // hHolder.ratingBar1.setRating(getJsonInt(obj, "starLevel"));

            aq.id(hHolder.iv_headimg).image(getJsonString(obj, "iconPhotoUrl"),
                    true, true, 200, 0, null, Constants.FADE_IN);
            if (!getJsonString(obj, "photoOne").endsWith("null") && !"".equals(getJsonString(obj, "photoOne"))) {
                aq.id(hHolder.photo_one).image(getJsonString(obj, "photoOne"),
                        false, true, 200, 0, preset, Constants.FADE_IN);
            } else {
                hHolder.photo_one.setImageResource(R.drawable.style_default);
            }
            if (!getJsonString(obj, "photoTwo").endsWith("null") && !"".equals(getJsonString(obj, "photoTwo"))) {
                aq.id(hHolder.photo_two).image(getJsonString(obj, "photoTwo"),
                        false, true, 200, 0, preset, Constants.FADE_IN);
            } else {
                hHolder.photo_two.setImageResource(R.drawable.style_default);
            }
            if (!getJsonString(obj, "photoThr").endsWith("null") && !"".equals(getJsonString(obj, "photoThr"))) {
                aq.id(hHolder.photo_three).image(getJsonString(obj, "photoThr"),
                        false, true, 200, 0, preset, Constants.FADE_IN);
            } else {
                hHolder.photo_three.setImageResource(R.drawable.style_default);
            }
        }


        public class DresserViewHolder extends RecyclerView.ViewHolder {
            String id;
            ImageView iv_headimg;
            Button iv_appointment;
            ImageView photo_one;
            ImageView photo_two;
            ImageView photo_three;
            TextView tv_style_intro;
            TextView tv_name;
            TextView tv_post;
            TextView tv_words;
            TextView tv_collections;
            TextView tv_orders;
            TextView tv_type;
            TextView tv_price;
            LinearLayout ll_coupon;

            // RatingBar ratingBar1;

            public DresserViewHolder(View itemView) {
                super(itemView);
                this.tv_style_intro = (TextView) itemView
                        .findViewById(R.id.tv_style_intro);
                this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
                this.tv_post = (TextView) itemView.findViewById(R.id.tv_post);
                this.tv_words = (TextView) itemView.findViewById(R.id.tv_words);
                this.tv_collections = (TextView) itemView
                        .findViewById(R.id.tv_collections);
                this.tv_orders = (TextView) itemView
                        .findViewById(R.id.tv_orders);
                this.tv_type = (TextView) itemView.findViewById(R.id.tv_type);
                this.tv_price = (TextView) itemView.findViewById(R.id.tv_price);
                this.iv_headimg = (ImageView) itemView
                        .findViewById(R.id.iv_headimg);
                this.ll_coupon = (LinearLayout) itemView
                        .findViewById(R.id.ll_coupon);
                this.iv_appointment = (Button) itemView
                        .findViewById(R.id.iv_appointment);

                this.photo_one = (ImageView) itemView
                        .findViewById(R.id.photo_one);
                this.photo_two = (ImageView) itemView
                        .findViewById(R.id.photo_two);
                this.photo_three = (ImageView) itemView
                        .findViewById(R.id.photo_three);
                // this.ratingBar1 = (RatingBar) itemView
                // .findViewById(R.id.ratingBar1);
                ll_coupon.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        mOnDresserClickListener.onDresserClick(CommonUtils
                                .getJsonString(array.get(getPosition()), "id"));
                    }
                });

                ((RelativeLayout) iv_headimg.getParent()).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        mOnDresserClickListener.onDresserClick(CommonUtils
                                .getJsonString(array.get(getPosition()), "id"));
                    }
                });
                photo_one.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        mOnDresserClickListener.onDresserClick(CommonUtils
                                .getJsonString(array.get(getPosition()), "id"));
                    }
                });
                photo_two.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        mOnDresserClickListener.onDresserClick(CommonUtils
                                .getJsonString(array.get(getPosition()), "id"));
                    }
                });
                photo_three.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        mOnDresserClickListener.onDresserClick(CommonUtils
                                .getJsonString(array.get(getPosition()), "id"));
                    }
                });
                this.iv_appointment.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        mOnDresserClickListener.onAppointmentClick(CommonUtils
                                .getJsonString(array.get(getPosition()), "id"));

                    }
                });

            }
        }

    }


    @Override
    public void onAppointmentClick(String id) {
        // TODO Auto-generated method stub
        BookActivity_.intent(this).extra("id", id).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Override
    public void onDresserClick(String id) {
        // TODO Auto-generated method stub
        HairDresserDetailActivity_.intent(HairDresserListActivity.this)
                .extra("id", id).start();
    }


    @ViewById
    Button btn_dresser;

    @Click
    void btn_dresser() {
        // HairDresserListActivity_.intent(this).start();
        clearPopup();
    }

    @Click
    void btn_home() {
//        typeVisible(View.INVISIBLE);
//        typeAreaVisible(View.INVISIBLE);
        clearPopup();
        MainActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_appointment() {
//        typeVisible(View.INVISIBLE);
//        typeAreaVisible(View.INVISIBLE);
        clearPopup();
        BookActivity_.intent(this).start();
    }

    @Click
    void btn_style() {
//        typeVisible(View.INVISIBLE);
//        typeAreaVisible(View.INVISIBLE);
        clearPopup();
        HairStyleListActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_userinfo() {
//        typeVisible(View.INVISIBLE);
//        typeAreaVisible(View.INVISIBLE);
        clearPopup();
        UserInfoActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    private long exitTime = 0;
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub

        if(rl_area.getVisibility()==View.VISIBLE||more.getVisibility()==View.VISIBLE){
            clearPopup();
            return ;
        }
        if((System.currentTimeMillis()-exitTime) > 2000){
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finishApplication();
        }
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        mLocationClient.stop();
        super.onStop();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            /**
             * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
             * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
             */
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            sb.append("\nCountryCode : ");
            sb.append(location.getCountryCode());
            sb.append("\nCountry : ");
            sb.append(location.getCountry());
            sb.append("\ncitycode : ");
            sb.append(location.getCityCode());
            sb.append("\ncity : ");
            sb.append(location.getCity());
            sb.append("\nDistrict : ");
            sb.append(location.getDistrict());
            sb.append("\nStreet : ");
            sb.append(location.getStreet());
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());
            sb.append("\nDescribe: ");
            sb.append(location.getLocationDescribe());
            sb.append("\nDirection(not all devices have value): ");
            sb.append(location.getDirection());
            sb.append("\nPoi: ");
            if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                for (int i = 0; i < location.getPoiList().size(); i++) {
                    Poi poi = (Poi) location.getPoiList().get(i);
                    sb.append(poi.getName() + ";");
                }
            }
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：km/h
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                // 运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }

            getLocation(location);

        }

    }

    private void getLocation(BDLocation location) {
        final String cityName = (location.getCity()).substring(0, (location.getCity().length()) - 1);
        localeCityName=cityName;
        city.setText(cityName);
        city_list.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                clearPopup();
                mLocationClient.stop();
                CityListActivity_.intent(HairDresserListActivity.this)
                        .extra("cityName", city_name).extra("localeCityName",localeCityName).startForResult(CITY_LIST_REQUEST_CODE);

            }
        });
        mLocationClient.stop();
    }
//
//    @Receiver(actions = HairDresserListActivity.CITY_REFRESH, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
//    protected void cityRefresh(Intent intent) {
//
//        String cityName = intent.getExtras().getString("cityName");
//        city_name=cityName;
//        if(cityName.equals(city_name)){
//            return;
//        }
//        if (cityName != null && !cityName.equals("")) {
//            city.setText(cityName);
//            clearArea();
//            clearDataset();
//            updateDataset(mPage);
//        }
//
//
//    }

    @Receiver(actions = "com.mlm.mlmapp.resetArea")
    protected void retArea(Intent intent) {
        mAdapter.selectText = "智能排序";
        mAdapter.notifyDataSetChanged();
        currentPrice = "";
        currentOrder = "";
        rating_desc = "";
        post_list = "";
        studio_list = "";
        areakey = "全部区域";
        dresserName = "";
        studioid = "";
        post_list = "";
        etSearch.setText("");
        clearDataset();
        updateDataset(mPage);
        btn_area.setText("全部区域");
        btn_area.setTextColor(greytext);
        btn_area.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_down), null);
        btn_all.setText("智能排序");
        btn_all.setTextColor(greytext);
        btn_all.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_down), null);
        btn_dresser_type.setTextColor(greytext);
        btn_dresser_type.setCompoundDrawables(null, null,
                CommonUtils.setButtonDrawableRight(this,
                        R.drawable.filter_default), null);
    }
    public void clearArea(){
        areakey = "全部区域";
        studioid="";
        btn_area.setText("全部区域");
        btn_area.setTextColor(greytext);
        btn_area.setCompoundDrawables(null, null, CommonUtils.setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_down), null);
    }
    static class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener {
        private String[] datas;
        String selectText;

        public MyAdapter(String[] datas) {
            this.datas = datas;
        }

        private OnRecyclerViewItemClickListener mOnItemClickListener = null;

        //define interface
        public interface OnRecyclerViewItemClickListener {
            void onItemClick(View view, String data);
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.dialog_header_item_view, viewGroup, false);
            ViewHolder vh = new ViewHolder(view);
            //将创建的View注册点击事件
            view.setOnClickListener(this);
            return vh;
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.mTextView.setText(datas[position]);
            //将数据保存在itemView的Tag中，以便点击时进行获取
            viewHolder.itemView.setTag(datas[position]);
            if (datas[position].equals(selectText)) {
                viewHolder.mTextView.setBackgroundColor(Color.parseColor("#9a9a9a"));
                viewHolder.mTextView.setTextColor(Color.WHITE);
            } else {
                viewHolder.mTextView.setBackgroundColor(Color.WHITE);
                viewHolder.mTextView.setTextColor(Color.parseColor("#9a9a9a"));
            }

        }

        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                //注意这里使用getTag方法获取数据
                selectText = (String) v.getTag();
                mOnItemClickListener.onItemClick(v, (String) v.getTag());
                notifyDataSetChanged();
            }
        }

        public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
            this.mOnItemClickListener = listener;
        }


        //获取数据的数量
        @Override
        public int getItemCount() {
            return datas.length;
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView mTextView;

            public ViewHolder(View view) {
                super(view);
                mTextView = (TextView) view.findViewById(R.id.tv_dialog_item);
            }
        }


    }

    public void refreshRecyclerView(String key) {
        //set row selected


        //setDataset and notify
        try {
            JSONArray array = studiosMap.get(key);

            studios.clear();
            for (int i = 0; i < array.length(); i++) {
                studios.add(array.getJSONObject(i));
            }
            rv_studio.getAdapter().notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    class CityAdapter extends
            RecyclerView.Adapter<CityAdapter.CityHolder> {
        private Context mContext;
        private List<JSONObject> array;

        public CityAdapter(Context con, List<JSONObject> array) {
            this.mContext = con;
            this.array = array;

        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        @Override
        public CityHolder onCreateViewHolder(ViewGroup parent, int arg1) {
            // TODO Auto-generated method stub
            CityHolder holder;
            holder = new CityHolder(LayoutInflater.from(
                    HairDresserListActivity.this).inflate(
                    R.layout.city_list_item, parent, false));
            return holder;

        }

        @Override
        public void onBindViewHolder(CityHolder holder, final int position) {
            // TODO Auto-generated method stub
            JSONObject obj = array.get(position);
            CityHolder hHolder = holder;
            final String keyFlag = CommonUtils.getJsonString(obj, "area");
            hHolder.value.setText(keyFlag);
            if (keyFlag.equals(areakey)) {
                if(position==0){
                    hHolder. itemView.setBackground(getResources().getDrawable(R.drawable.grey_round_left_top));
                }else if(position==array.size()-1){
                    hHolder. itemView.setBackground(getResources().getDrawable(R.drawable.grey_round_left_bottom));
                }else {
                    hHolder. itemView.setBackground(getResources().getDrawable(R.drawable.grey_bg));
                }
            } else {
                if(position==0){
                    hHolder.itemView.setBackground(getResources().getDrawable(R.drawable.white_round_left_top));
                }else if(position==array.size()-1){
                    hHolder.itemView.setBackground(getResources().getDrawable(R.drawable.white_round_left_bottom));
                }else {
                    hHolder. itemView.setBackground(getResources().getDrawable(R.drawable.white_bg));
                }
            }

            hHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    areakey = keyFlag;

                    CityAdapter.this.notifyDataSetChanged();
                    refreshRecyclerView(keyFlag);
                    if(position==0){
                        view.setBackground(getResources().getDrawable(R.drawable.grey_round_left_top));
                    }else if(position==array.size()-1){
                        view.setBackground(getResources().getDrawable(R.drawable.grey_round_left_bottom));
                    }
                }
            });

        }


        public class CityHolder extends RecyclerView.ViewHolder {
            TextView value;


            public CityHolder(View itemView) {
                super(itemView);
                this.value = (TextView) itemView.findViewById(R.id.tv_name);


            }
        }

    }

    class StudioAdapter extends
            RecyclerView.Adapter<StudioAdapter.StudioHolder> {
        private Context mContext;
        private List<JSONObject> array;

        public StudioAdapter(Context con, List<JSONObject> array) {
            this.mContext = con;
            this.array = array;

        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        @Override
        public StudioHolder onCreateViewHolder(ViewGroup parent, int arg1) {
            // TODO Auto-generated method stub
            StudioHolder holder;
            holder = new StudioHolder(LayoutInflater.from(
                    HairDresserListActivity.this).inflate(
                    R.layout.area_studio_list_item, parent, false));
            return holder;

        }

        @Override
        public void onBindViewHolder(StudioHolder holder, int position) {
            // TODO Auto-generated method stub
            JSONObject obj = array.get(position);
            StudioHolder hHolder = holder;


            final String id = CommonUtils.getJsonString(obj, "id");
            final String name = CommonUtils.getJsonString(obj, "names");
            hHolder.value.setText(name);
            if (id.equals(studioid)) {
                hHolder.value.setTextColor(Color.RED);
            } else {
                hHolder.value.setTextColor(Color.parseColor("#404040"));
            }
            hHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    rl_area.setVisibility(View.INVISIBLE);
                    btn_area.setText(name);
                    if (!name.equals("全部区域")) {
                        btn_area.setTextColor(Color.parseColor("#ea2929"));
                        btn_area.setCompoundDrawables(null, null, CommonUtils
                                .setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_up), null);
                    } else {
                        btn_area.setTextColor(Color.parseColor("#9a9a9a"));
                        btn_area.setCompoundDrawables(null, null, CommonUtils
                                .setButtonDrawableRight(HairDresserListActivity.this, R.drawable.screen_arrow_down), null);
                    }
                    studioid = id;
                    clearDataset();
                    updateDataset(mPage);

                }
            });

        }


        public class StudioHolder extends RecyclerView.ViewHolder {
            TextView value;


            public StudioHolder(View itemView) {
                super(itemView);
                this.value = (TextView) itemView.findViewById(R.id.tv_name);

            }
        }

    }

}
